<template>
  <div class="app-container">
    <!-- 角色列表 -->
    <el-table :data="examRoleList" row-key="id">
      <el-table-column type="index" label="序号" width="260" />
      <!-- <el-table-column prop="id" label="id" width="200" /> -->
      <el-table-column prop="roleName" label="角色名称" width="200" />
    </el-table>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button icon="el-icon-plus" plain size="mini" @click="handleAdd"
          >新增</el-button
        >
        <el-button plain size="mini" @click="handleSelectAll">全选</el-button>
        <el-button
          plain
          size="mini"
          type="danger"
          @click="handleDelete"
          :disabled="multiple"
          >删除</el-button
        >
        <el-button
          plain
          size="mini"
          :disabled="multiple"
          @click="handleChangeStatus(1)"
          >锁定</el-button
        >
        <el-button
          plain
          size="mini"
          :disabled="multiple"
          @click="handleChangeStatus(0)"
          >解锁</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      ref="table"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" width="55" />
      <el-table-column
        label="用户名"
        align="center"
        prop="username"
        width="140"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="添加时间	"
        align="center"
        prop="createTime"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="角色"
        align="center"
        prop="type"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.type==3?"学员":"审批人员" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        prop="status"
        width="90"
        :formatter="statusFormat"
      />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="角色" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio
              v-for="item in examRoleList"
              :key="item.id"
              :label="item.id"
              >{{ item.roleName }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listType,
  addType,
  getType,
  delType,
  updateType,
  changeStatus
} from "@/api/cms/user";
import { getPage as getCategoryPage } from "@/api/cms/category";

export default {
  name: "Admin",
  data() {
    return {
      examRoleList: [
        {
          id: 3,
          roleName: "学员"
        },
        {
          id: 4,
          roleName: "审批人员"
        },
        // {
        //   id: 3,
        //   roleName: "管理员"
        // }
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // type: 0,
        isExam: 1,
      },
      // 表单参数
      form: {
        cmsPermissionList: []
      },
      category: [],
      categoryData: []
    };
  },
  computed: {
    // 表单校验
    rules() {
      return {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [
          {
            required: this.form.id ? false : true,
            message: "密码不能为空",
            trigger: "blur"
          }
        ],
        type: [
          { required: true, message: "请选择角色", trigger: "blur" }
        ]
      };
    }
  },
  created() {
    getCategoryPage().then(response => {
      this.categoryData = response.data;
      this.category = this.handleTree(response.data, "categoryId");
      category.forEach(item => {
        if (item.children) {
          item.children.push({
            categoryId: -1 * item.categoryId,
            categoryName: "考试专用",
            parentId: item.categoryId,
            pid: item.categoryId
          });
        }
      });
      this.getList();
    });
  },
  methods: {
    permissionFormat(cmsPermissionList) {
      let str = [];
      if (this.categoryData && this.categoryData.length > 0) {
        cmsPermissionList.forEach(item => {
          this.categoryData.forEach(category => {
            if (item.categoryId === category.categoryId) {
              str.push(category.categoryName);
            }
          });
        });
      }
      return str.join(" | ");
    },
    getList() {
      this.loading = true;
      listType(this.queryParams).then(response => {
        this.list = response.rows.map(item => {
          item.cmsPermissionText = item.cmsPermissionList.map(
            permission => permission.categoryId
          );
          return item;
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    statusFormat(row, column) {
      return row.status == 0 ? "正常" : "锁定";
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        username: undefined,
        password: undefined,
        cmsPermissionList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加人员";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getType(id).then(response => {
        response.data.password = "";
        this.form = response.data;
        this.form.cmsPermissionList = this.form.cmsPermissionList.map(
          x => x.categoryId
        );
        this.open = true;
        this.title = "修改人员";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const cmsPermissionList = this.form.cmsPermissionList.map(x => ({
            categoryId: x
          }));

          if (this.form.id != undefined) {
            updateType({ ...this.form, cmsPermissionList }).then(
              response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            );
          } else {
            addType({ ...this.form, cmsPermissionList }).then(
              response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            );
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.id || this.ids;
      this.$confirm(`是否确认删除编号为[${Ids}]的管理员?`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delType(Ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有类型数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportType(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    },
    // 全选
    handleSelectAll() {
      this.$refs.table.toggleAllSelection();
    },
    // 变更状态
    handleChangeStatus(status) {
      changeStatus({
        ids: this.ids,
        status
      }).then(response => {
        this.msgSuccess("修改成功");
        this.getList();
      });
    }
  }
};
</script>
